package homework4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class ServerTest {

	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket s = null;
		ObjectInputStream ois = null;
		ObjectOutputStream oos = null;

		try {
			// 1.创建ServerSocket类型的对象并提供端口号
			serverSocket = new ServerSocket(8888);

			// 2.等待客户端的连接请求，调用accept方法
			System.out.println("等待客户端的连接请求...");
			s = serverSocket.accept();
			System.out.println("客户端连接成功！");
			// 3.使用输入输出流进行通信
			ois = new ObjectInputStream(s.getInputStream());
			oos = new ObjectOutputStream(s.getOutputStream());

			while (true) {
				// 实现对客户端发来字符串内容的接收并打印
				UserMessage obj = (UserMessage) ois.readObject();
				System.out.println("客户端发数据内容是：" + obj);
				String s1 = obj.getUser().getName();
				String s2 = obj.getUser().getPassword();
				// 当客户端发来的内容为"bye"时，则聊天结束
				if ("bye".equalsIgnoreCase(s1) || "bye".equalsIgnoreCase(s2)) {
					System.out.println("客户端链接断开！");
					break;
				}
				if (s1.equals("admin") && s2.equals("123456")) {
					// 实现服务器向客户端返回对象
					oos.writeObject(new UserMessage("success", new User(s1, s2)));
					System.out.println("服务器发送数据成功！");
				} else {
					// 实现服务器向客户端返回对象
					oos.writeObject(new UserMessage("fail", new User(s1, s2)));
					System.out.println("服务器发送数据成功！");
				}

			}
		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (null != oos) {
				try {
					oos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				if (null != ois) {
					ois.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (null != s) {
					s.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 4.关闭Socket并释放有关的资源
			if (null != serverSocket) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}
}
